<template>
  <div>
    <van-nav-bar
      :title="data.title"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    ></van-nav-bar>
    <main>
      <!-- 标题区 -->
      <header class="md_header">
        <h1>
          <span class="tag" v-if="data.top">置顶</span>
          <span class="tag" v-else-if="data.good">精华</span>
          {{ data.title }}
        </h1>
        <van-checkbox
          v-if="accesstoken"
          v-model="collect"
          :label="collect_txt"
          uncheck-icon="favorite_border"
          checked-icon="favorite"
        ></van-checkbox>
        <div class="label">
          <span>发布于 {{ data.create_at | timeago }}</span>
          <span>作者 {{ data.author.loginname }}</span>
          <span>{{ data.visit_count }} 次浏览</span>
          <span>来自 {{ data.tab | tab }}</span>
        </div>
      </header>
      <!-- 内容区 -->
      <article class="md_content" v-html="data.content"></article>
      <!-- 评论区 -->
      <van-list v-if="data.replies.length" class="replies">
        <van-cell>{{ data.replies.length }}条回复</van-cell>
        <van-cell
          class="reply"
          v-for="(list, index) in data.replies"
          :key="list.id"
        >
          <section class="msg">
            <div class="author">
              <router-link
                :to="{
                  path: '/user',
                  query: { user: list.author.loginname }
                }"
                class="author-avatar"
                :src="list.author.avatar_url"
                tag="img"
                alt="user"
              >
              </router-link>
              <span class="name">{{ list.author.loginname }}</span>
              <span class="name"
                >{{ index + 1 }}楼 • {{ list.create_at | timeago }}</span
              ><!-- 登录状态下点赞 -->
              <span @click="open" v-if="accesstoken" class="ups">
                <van-icon
                  class="up-icon"
                  @click="like(index)"
                  name="thumb-circle-o"
                  :size="16"
                ></van-icon>
                <span>{{ list.ups.length }}</span>
                <van-button
                  type="primary"
                  size="small"
                  @click="changeReply(index)"
                  >回复</van-button
                >
              </span>
              <span @click="open" v-if="list.ups.length && !accesstoken">
                <van-icon name="thumb-circle-o" size="16"></van-icon>
                <span>{{ list.ups.length }}</span>
              </span>
            </div>
            <!-- 未登录状态下点赞 -->
          </section>
          <p v-html="list.content"></p>
          <!--回复内容提供-->
          <van-dialog
            width="800px"
            v-if="accesstoken"
            v-model="list.reply_show"
            title="回复内容"
            :show-cancel-button="false"
            :showConfirmButton="false"
          >
            <Editor v-model="single_reply"></Editor>
            <van-row>
              <van-col span="12"
                ><van-button
                  class="dialog-button"
                  type="primary"
                  @click="exit_single_reply_content(index)"
                  >取消</van-button
                ></van-col
              >
              <van-col span="12">
                <van-button
                  type="primary"
                  class="dialog-button"
                  @click="single_reply_content(index)"
                  >回复</van-button
                ></van-col
              >
            </van-row>
          </van-dialog>
        </van-cell>
      </van-list>
      <van-list v-if="accesstoken" class="replies">
        <van-cell>添加回复</van-cell>
        <van-cell>
          <van-field
            multi-line
            v-model="reply"
            class="reply"
            placeholder="请输入回复内容..."
          ></van-field>
          <van-button type="primary" @click="reply_content">回复</van-button>
        </van-cell>
      </van-list>
    </main>
  </div>
</template>

<script>
import Vue from "vue";
import * as timeago from "timeago.js";
import Editor from "@tinymce/tinymce-vue";
export default {
  name: "PassageContent",
  // 对象
  components: { Editor },
  data() {
    return {
      accesstoken: "",
      user_id: "",
      data: {
        author: {},
        replies: {}
      },
      user: {},
      dialog: false,
      reply: "",
      single_reply: "",
      isReply: false,
      tips: "",
      collect: false,
      collect_txt: "收藏主题",
      loginname: "",
      collected: false
    };
  },
  created() {
    this.user.accesstoken = localStorage.getItem("accesstoken");
    this.user.user_id = localStorage.getItem("user_id");
    this.user.loginname = localStorage.getItem("loginname");
    this.getData();
    // console.log(this.loginname)
  },
  watch: {
    collect(newVal) {
      if (newVal) {
        this.on_collect();
        this.collect_txt = "取消收藏";
      } else {
        this.off_collect();
        this.collect_txt = "收藏主题";
      }
    }
  },
  filters: {
    timeago(val) {
      let time = new Date(val);
      return timeago.format(time, "zh_CN"); //将UTC时间转换格式---> 几天前,几小时前...
    },
    tab(val) {
      let valMap = new Map([
          ["share", "分享"],
          ["ask", "问答"],
          ["job", "招聘"]
        ]),
        result = valMap.get(val);
      return result;
    }
  },
  mounted() {},
  methods: {
    getData() {
      // 主题详情
      let id = this.$route.query.id;
      this.$fetch.get("/topic/" + id).then(response => {
        this.data = response.data;
        console.log(this.data);
        //每一项回复，添加标记
        console.log("文章内容");
        this.data.replies.map(item => {
          item.reply_show = false;
        });
      });
      if (this.accesstoken) {
        this.isCollected();
      }
    },
    isCollected() {
      //收藏
      this.$fetch.get("/user/" + this.user.loginname).then(response => {
        // 获取收藏主题数组
        let arr = response.data.collect_topics;
        //本页主题id
        let collect_id = this.data.id;
        //find 本页主题是否在已收藏列表
        arr.find(function(item) {
          if (item.id === collect_id) {
            this.collect = true;
            this.collect_txt = "收藏主题";
          }
        });
      });
    },
    goBack() {
      this.$router.go(-1);
      // this.$router.back()
    },
    open() {
      this.dialog = true;
    },
    close() {
      this.dialog = false;
      this.isReply = false;
    },
    reply_content() {
      // 添加评论
      let id = this.$route.query.id;
      this.$fetch
        .post("/topic/" + id + "/replies", {
          accesstoken: this.accesstoken,
          content: this.reply
        })
        .then(response => {
          this.tips = "回复成功！";
          this.isReply = true;
          setTimeout(function() {
            this.isReply = false;
          }, 1500);
          this.getData();
          this.reply = "";
        })
        .catch(error => {
          this.tips = "请输入回复内容...";
          this.isReply = true;
          setTimeout(function() {
            this.isReply = false;
          }, 1500);
        });
    },
    like(index) {
      //点赞
      let reply_id = this.data.replies[index].id;
      this.$fetch
        .post("/reply/" + reply_id + "/ups", {
          accesstoken: this.accesstoken
        })
        .then(response => {
          // console.log(response.data)
          this.getData();
        });
    },
    single_reply_content(index) {
      // 对评论的回复
      let id = this.$route.query.id;
      this.$fetch
        .post("/topic/" + id + "/replies", {
          accesstoken: this.accesstoken,
          content: this.single_reply,
          reply_id: this.data.replies[index].id
        })
        .then(response => {
          this.tips = "回复成功！";
          this.isReply = true;
          setTimeout(function() {
            this.isReply = false;
          }, 1500);
          this.getData();
          this.single_reply = "";
        })
        .catch(err => {
          this.tips = "请输入回复内容...";
          this.isReply = true;
          setTimeout(function() {
            this.isReply = false;
          }, 1500);
        });
    },
    changeReply(index) {
      //点击对评论进行回复
      let arr = this.data.replies;
      arr.map((item, i) => {
        index === i
          ? Vue.set(item, "reply_show", true)
          : Vue.set(item, "reply_show", false);
      });

      this.single_reply = "@" + this.data.replies[index].author.loginname + " ";
    },
    exit_single_reply_content(index) {
      //取消对评论的回复，清空内容
      this.single_reply = "";
      let arr = this.data.replies;
      arr[index].reply_show = false;
      Vue.set(arr, index, arr[index]);
    },
    on_collect() {
      //收藏主题

      this.$fetch
        .post("/topic/collect", {
          accesstoken: this.accesstoken,
          topic_id: this.data.id
        })
        .then(function(response) {
          // console.log(response.data)
        });
    },
    off_collect() {
      // 取消收藏

      this.$fetch
        .post("/topic/de_collect", {
          accesstoken: this.accesstoken,
          topic_id: this.data.id
        })
        .then(response => {
          console.log(response.data);
        });
    }
  }
};
</script>

<style scoped>
.author {
}
.name {
  color: lightseagreen;
}
.author-avatar {
  width: 50px;
  height: 50px;
  border-radius: 10px;
}

.up-icon {
  color: #00a854;
}
.up-icon:hover {
  cursor: pointer;
  color: #009688;
}

.dialog-button {
  padding: 10px 40px;
}
</style>
